import { Injectable } from '@angular/core';
import { Http, ResponseContentType } from '@angular/http';
import { environment as env } from '../../environments/environment';
import { Subscription } from 'rxjs/Subscription';


declare global {
  interface Promise<T> {
    subscription: Subscription;

    cancel();
  }
}

Promise.prototype.cancel = function () {
  if (this.subscription) {
    this.subscription.unsubscribe();
  }

};


interface Options {
  method: string;
  url: string;
  params?: any;
  simulate: boolean;
  body?: any;
}



@Injectable()
export class BaseHttpService {


  private successHandler(response, opts: Options, resolve, reject) {
    const json = response.json();
    resolve(json);
    // if (json.resultcode) {
    //   resolve(json);
    // } else {
    //   reject(json);
    // }
  }

  private errorHandler(error, opts: Options, reject) {
    console.warn(error, opts);
    reject({ success: false, errMsgEn: 'server error' });
  }


  private completeHandler(opts) {

  }

  constructor(private http: Http) {
  }

  request<T>(opts: Options) {
    //const path ="http://localhost:52128/";// opts.simulate ? env.local + opts.url + '.json' : env.api + opts.url;
    let subscription: Subscription = null;
    if (opts.simulate) {
      opts.method = 'GET';
    }
    //opts.params = Object.assign({}, {token: localStorage['token']}, opts.params);
    //this.message.showLoading();
    const promise = new Promise<T>((resolve, reject) => {
      console.log(opts.url, opts.params, opts.body);
      subscription = this.http.request(opts.url, {
        method: opts.method,
        params: opts.params,
        body: opts.body,
        responseType: ResponseContentType.Json,
      }).subscribe(response => {
        this.successHandler(response, opts, resolve, reject);
      }, error => {
        this.errorHandler(error, opts, reject);
      }, () => {
        //this.message.hideLoading();
        this.completeHandler(opts);
      });
    });
    promise.subscription = subscription;
    // promise.catch(json => {
    //   // 避免控制台报错
    //   console.log(json);
    // });
    return promise;
  }

  get<T= any>(url, data, simulate: boolean = false): Promise<T> {
    return this.request<T>({
      method: 'GET',
      url: url,
      params: data,
      simulate: simulate
    });
  }

  post<T= any>(url, data, simulate: boolean = false): Promise<T> {
    return this.request<T>({
      method: 'POST',
      url: url,
      params: data,
      simulate: simulate
    });
  }

  postJson<T= any>(url, data, params = null, simulate: boolean = false): Promise<T> {
    return this.request<T>({
      method: 'POST',
      url: url,
      params: params,
      body: data,
      simulate: simulate
    });
  }
}
